package com.fg.cloud.factory.controller.agency;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.construction.Tree;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.framework.controller.BaseController;
import com.fg.cloud.manager.entry.agency.AgencyAreaEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyAreaVo;
import com.fg.cloud.manager.entry.factory.vo.FactoryUserVo;
import com.fg.cloud.manager.service.agency.AgencyAreaService;
import com.google.common.collect.Lists;

/**
 * 经销商-区域controller
 * @author around
 * @date 2017-6-23
 */
@Controller
@RequestMapping("/agencyArea")
public class AgencyAreaController extends BaseController {

	@Autowired
	private AgencyAreaService agencyAreaService;
	
	/**
	 * 详情页信息封装查询
	 * @param request
	 * @param session
	 * @param address
	 * @return String 
	 */
	@RequestMapping(value = "/detail", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void openPage(HttpServletRequest request, HttpServletResponse response, 
			AgencyAreaEntity address) {
		AgencyAreaEntity entity = agencyAreaService.find(address.getId());
		if(entity == null)
			doResult(response, false, StatusCode.FINDERROR, null, ResultType.FIND_FAULT);
		else
			doResult(response, true, StatusCode.FINDSUCCESS, entity, ResultType.FIND_SUCCESS);
	}
	
	/**
	 * 分页查询，确认厂商对应的区域设置
	 * @param request
	 * @param session
	 * @param facId
	 */
	@RequestMapping(value = "/findList", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void findList(HttpServletRequest request, HttpServletResponse response, 
			Long facId) {
		FactoryUserVo user = getCurrentFactoryUser();
		try {
			List<AgencyAreaVo> areaList = agencyAreaService.findList(facId == null ? user.getFacId() : facId);
			doResult(response, true, StatusCode.FINDSUCCESS, areaList, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			doResult(response, false, StatusCode.FINDERROR, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/selectPage", method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public PageUtils<AgencyAreaVo> selectPage(HttpServletRequest req, HttpServletResponse resp, Long facId) {
		try {
			List<AgencyAreaVo> areaList = agencyAreaService.findList(facId);
			PageUtils<AgencyAreaVo> pageinfo = new PageUtils<>();
			pageinfo.setRows(areaList);
			return pageinfo;
		} catch (Exception e) {
			e.printStackTrace();
			return new PageUtils<>();
		}	
	}

	/**
	 * 新增/保存信息   
	 * 说明，此处传参，前台需要携带 上级区域numbe+id，格式：number_id
	 * @param request
	 * @param response
	 * @param area AgencyAreaEntity
	 */
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
	@ResponseBody
	public void saveOrUpdate(HttpServletRequest request, HttpServletResponse response, 
			AgencyAreaVo area) {
		try {
			boolean flag = agencyAreaService.verifyUniquely(area.getId(), area.getName(),
					null == area.getFacId() ? getCurrentFactoryUser().getFacId() : area.getFacId());
			if (!flag) {
				doResult(response, false, StatusCode.SAVEERROR, null, "重复的区域名称");
				return;
			}
			setUpdateInfo(area, request);
			//setNumber(area);
			//id为空新增、不为空保存
			if(null == area.getId()) {
				area.setFacId(getCurrentFactoryUser().getFacId());
				setCreateInfo(area, request);
				flag = agencyAreaService.insertSelective(area);
			} else {
				flag = agencyAreaService.updateByPrimaryKeySelective(area);
			}
			doResult(response, flag, flag ? StatusCode.SAVESUCCESS:StatusCode.SAVEERROR, null, flag ? ResultType.SAVE_SUCCESS:ResultType.SAVE_FAULT);
		} catch (Exception e) {
			doResult(response, false, StatusCode.SAVEERROR, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除信息
	 * @param request
	 * @param response
	 * @param ids String => x,x,x
	 * @throws IOException 
	 */
	@RequestMapping(value = "/delete", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void deletes(HttpServletRequest request, HttpServletResponse response, 
			Long id, String number) throws IOException {
		/*//判断区域是否被引用
		 if(agencyAreaService.selectAgencyByArea(id) > 0) {
			doResult(response, flag, StatusCode.REMOVEERROR, null, "该区域已被经销商引用");
			return;
		}
		flag = agencyAreaService.delete(id) > 0 ? true : false;
		*/
		try {
			if(StringUtils.isEmpty(number) || id == null) {
				doResult(response, false, StatusCode.REMOVEERROR, null, ResultType.INPUT_ERROR);
				return;
			}
			boolean flag = agencyAreaService.updateStatus(id, number+"_"+id);
			
			doResult(response, flag, flag ? StatusCode.REMOVESUCCESS:StatusCode.REMOVEERROR, 
					null, flag ? ResultType.REMOVE_SUCCESS : ResultType.REMOVE_FAULT);
		} catch (Exception e) {
			doResult(response, false, StatusCode.REMOVEERROR, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 分页查询，确认厂商对应的区域设置
	 * @param request
	 * @param session
	 * @param facId
	 */
	@RequestMapping(value = "/findListByUser", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void findListByUser(HttpServletRequest request, HttpServletResponse response, 
			Long userId) {
		if (null == userId) {
			doResult(response, false, StatusCode.FINDERROR, null, "用户ID为空");
			return;
		}
		try {
			List<Tree> areaList = agencyAreaService.findListByUser(
					getCurrentFactoryUser().getFacId(), userId);
			doResult(response, true, StatusCode.FINDSUCCESS, areaList, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			doResult(response, false, StatusCode.FINDERROR, null, e.getMessage());
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:根据厂商ID查询该厂商所有的经销商区域
	 * @param req
	 * @param resp
	 * @param facId
	 * @author dingjiang
	 * @date 2017年11月10日上午10:33:29
	 */
	@RequestMapping(value = "/findTreeList", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public List<Tree> findTreeList(HttpServletRequest req, HttpServletResponse resp, Long facId) {
		try {
			if ( null == facId ) {
				doResult(resp, false, StatusCode.FINDERROR, null, "请选择厂商");
				return Lists.newArrayList();
			}
			List<Tree> areaList = agencyAreaService.findTreeList(facId);
			/*doResult(resp, true, StatusCode.FINDSUCCESS, areaList, ResultType.FIND_SUCCESS);*/
			return areaList;
		} catch (Exception e) {
			/*doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());*/
			e.printStackTrace();
			return Lists.newArrayList();
		}
	}
	
	
	/**
	 * 设置区域编码规则，当前级规则等于上级ID_上级number
	 * @param area
	 */
	/*private void setNumber(AgencyAreaVo area) {
		if(null == area.getPid()) area.setNumber("0");
		else if(0 == area.getPid()) area.setNumber("0");
		else area.setNumber(area.getPid() + "_" + area.getPnumber());
	}*/
}
